import { defineStore } from "pinia";
import systemApi from "@/api/system";
import newsApi from "@/api/news";
import { getToken, clearToken } from "@/utils/auth";

export const useUserStore = defineStore("user", () => {
  const router = useRouter();
  const route = useRoute();

  const userInfo = ref(null);
  const userAvatar = computed(() => {
    if (userInfo.value?.avatar) {
      return `${import.meta.env.VITE_BASE_URL}${userInfo.value.avatar}`;
    }
    return "/svg/avatar.svg";
  });

  const getUserInfo = async () => {
    if (!getToken()) return;
    const { user } = await systemApi.getUserInfo();
    userInfo.value = user;
  };

  const logout = () => {
    userInfo.value = null;
    clearToken();
    // setTimeout(() => {
    //   router.push({
    //     path: "/",
    //     replace: true,
    //   });
    // }, 1000);
  };

  const goLogin = () => {
    if (route.path === "/index") return;
    router.push({
      name: "Login",
      query: {
        redirect: route.fullPath,
      },
      replace: true,
    });
  };

  const updateUserInfo = (info) => {
    userInfo.value = {
      ...userInfo.value,
      ...info,
    };
  };

  const pollingTimer = ref(null);
  const unreadNum = ref({
    inform: 0,
    notice: 0,
  });

  // 获取通知公告未读
  const getNoticeNum = async () => {
    if (!userInfo.value) return;
    const { data } = await newsApi.getNoticeNum();
    unreadNum.value = data;
  };
  const pollingGetNoticeNum = () => {
    pollingTimer.value = setInterval(
      (() => (getNoticeNum(), getNoticeNum))(),
      10000
    );
  };

  watch(
    () => userInfo.value,
    (val) => {
      if (val) {
        pollingGetNoticeNum();
      } else if (pollingTimer.value) {
        clearInterval(pollingTimer.value);
        pollingTimer.value = null;
      }
    }
  );

  return {
    userInfo,
    userAvatar,
    getUserInfo,
    logout,
    goLogin,
    updateUserInfo,
    unreadNum,
  };
});
